//
//  UCMapView+GSExtension.m
//  AeroMapSDK
//
//  Created by 北京国泰北斗科技有限公司 on 2017/3/21.
//  Copyright © 2017年 北京国泰北斗科技有限公司. All rights reserved.
//

#import "UCMapView+GSExtension.h"
#import <CoreText/CoreText.h>
#import "Public.h"

@implementation UCMapView (GSExtension)
- (CLLocationCoordinate2D)wgs84ToGcj02WithLocation:(CLLocationCoordinate2D)locaion{
    
    double a = 6378245.0, f = 1 / 298.3;
    double b = a * (1 - f);
    double ee = 1 - (b * b) / (a * a);
    
    double lon = locaion.longitude;
    double lat = locaion.latitude;
    
    double dLon = [self lonToGcj02:lon - 105.0 with:lat - 35.0];
    double dLat = [self latToGcj02:lon - 105.0 with:lat - 35.0];
    
    double radLat = lat / 180.0 * M_PI;
    double magic = sin(radLat);
    
    magic = 1 - ee * magic * magic;
    double sqrtMagic = sqrt(magic);
    dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI);
    dLat = (dLat * 180.0)
				/ ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI);
    
    double x = lon + dLon;
    double y = lat + dLat;
    
    CLLocationCoordinate2D position = CLLocationCoordinate2DMake(y, x);
    return position;
}

- (double)lonToGcj02:(double)x with:(double)y{
    
    double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
    ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0;
    return ret;
}

- (double)latToGcj02:(double) x with:(double)y{
    double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0;
    ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0;
    return ret;
}

- (CLLocationCoordinate2D)gcj02ToWgs84WithLocation:(CLLocationCoordinate2D)locaion{
    
    double lon = locaion.longitude;
    double lat = locaion.latitude;
    
    CLLocationCoordinate2D position = [self wgs84ToGcj02WithLocation:locaion];
    
    double dx = position.longitude - locaion.longitude;
    double dy = locaion.latitude - locaion.latitude;
    
    while (fabs(dx) > 1e-6 || fabs(dy) > 1e-6) {
        lon -= dx / 2;
        lat -= dy / 2;
        
        position = [self wgs84ToGcj02WithLocation:CLLocationCoordinate2DMake(lat, lon)];
        dx = position.longitude - locaion.longitude;
        dy = position.latitude - locaion.latitude;
    }
    
    return CLLocationCoordinate2DMake(lat, lon);
}

- (UIImage *)iconForText:(NSString *)text withBaseImage:(UIImage *)image {
    
    UIFont *font = [UIFont boldSystemFontOfSize:12];
    CGSize size = image.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *attributes = @{
                                 NSFontAttributeName : font,
                                 NSParagraphStyleAttributeName : paragraphStyle,
                                 NSForegroundColorAttributeName : [UIColor blackColor]
                                 };
    CGSize textSize = [text sizeWithAttributes:attributes];
    CGRect textRect = CGRectInset(rect, (rect.size.width - textSize.width) / 2,
                                  (rect.size.height - textSize.height-4) / 2);
    [text drawInRect:CGRectIntegral(textRect) withAttributes:attributes];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)generateClusterIconWithCount:(NSUInteger)count{
    
    int diameter = 26;
    CGRect rect = CGRectMake(0, 0, diameter, diameter);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    @autoreleasepool {
        
        [[UIColor colorWithPatternImage:MYBUNDLE_IMAGE_PATH(@"landing_points")] setFill];
        
        CGContextSetLineWidth(ctx, 0);
        CGRect circleRect = CGRectMake(0, 0, diameter, diameter);
        circleRect = CGRectInset(circleRect, 0, 0);
        CGContextFillEllipseInRect(ctx, circleRect);
        CGContextStrokeEllipseInRect(ctx, circleRect);
        
        if (count > 0) {
            CTFontRef myFont = CTFontCreateWithName( (CFStringRef)@"Helvetica-Bold", 11.0f, NULL);
            UIColor *fontColor;
            fontColor = [UIColor blackColor];
            NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)myFont, (id)kCTFontAttributeName,fontColor, (id)kCTForegroundColorAttributeName, nil];
            
            // create a naked string
            NSString *string = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)count];
            
            NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:string attributes:attributesDict];
            
            // flip the coordinate system
            CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
            CGContextTranslateCTM(ctx, 0, diameter);
            CGContextScaleCTM(ctx, 1.0, -1.0);
            
            CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(stringToDraw));
            CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter,CFRangeMake(0, stringToDraw.length),NULL,                   CGSizeMake(diameter, diameter),NULL);
            float midWidth = diameter / 2;
            midWidth -= suggestedSize.width / 2;
            
            CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)stringToDraw);
            CGContextSetTextPosition(ctx, midWidth, 11);
            CTLineDraw(line, ctx);
            
            CFRelease(myFont);
            CFRelease(line);
            CFRelease(frameSetter);
        }
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
}
@end
